package com.cloud.common.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class AliUploadHelper {

    private final AliOssRequest aliOssRequest;

    public AliUploadHelper(AliOssRequest aliOssRequest) {
        this.aliOssRequest = aliOssRequest;
    }

//    public AliUploadHelper() {
//        aliOssRequest = null;
//    }

    public AliOssResponse uploadSimple(InputStream file, String key) {
        List<AliOssUploadRequest> list = new ArrayList<AliOssUploadRequest>() {{
            AliOssUploadRequest req = new AliOssUploadRequest();
            req.setFiledir(key);
            req.setFile(file);
            add(req);
        }};

        List<AliOssResponse> ossResponseList = uploadSimple(list);
        if (ossResponseList == null || ossResponseList.size() <= 0) {
            return new AliOssResponse();
        }
        return ossResponseList.get(0);
    }


    public List<AliOssResponse> uploadSimple(List<AliOssUploadRequest> list) {
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = aliOssRequest.getEndpoint();
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
        String accessKeyId = aliOssRequest.getAccessKeyId();
        String accessKeySecret = aliOssRequest.getAccessKeySecret();

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);


        for (AliOssUploadRequest item : list) {

            // 创建PutObjectRequest对象。
            // <yourObjectName>表示上传文件到OSS时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
            PutObjectRequest putObjectRequest = new PutObjectRequest(
                    aliOssRequest.getBucketName(),
                    item.getFiledir(),
                    //                new ByteArrayInputStream(content.getBytes())
                    item.getFile()
            );
// 上传字符串。
            ossClient.putObject(putObjectRequest);
        }

        // 如果需要上传时设置存储类型与访问权限，请参考以下示例代码。
        // ObjectMetadata metadata = new ObjectMetadata();
        // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
        // metadata.setObjectAcl(CannedAccessControlList.Private);
        // putObjectRequest.setMetadata(metadata);

        // 关闭OSSClient。
        ossClient.shutdown();
        List<AliOssResponse> aliOssResponseList = new ArrayList<>();

        for (AliOssUploadRequest item : list) {
            AliOssResponse aliOssResponse = new AliOssResponse();
            aliOssResponse.setPath(item.getFiledir());
            aliOssResponse.setAbsolutePath(aliOssRequest.getImgUrl() + item.getFiledir());
            aliOssResponseList.add(aliOssResponse);
        }
        return aliOssResponseList;
    }

    public AliOssResponse uploadFile(InputStream inputStream, String fileName, boolean setDis) {
        OSS ossClient = new OSSClientBuilder().build(aliOssRequest.getEndpoint(), aliOssRequest.getAccessKeyId(), aliOssRequest.getAccessKeySecret());
        // 上传文件流。
        String bucketName = aliOssRequest.getBucketName();
        ObjectMetadata meta = new ObjectMetadata();
//        fileName = DateUtils.getDangQianShiJianHaoMiao() + fileName;
        // 添加时间戳。
        if (setDis) {
            String disposition = "attachment;filename=\"" + fileName + "\"";
            meta.setContentDisposition(disposition);
        }
        meta.setContentType("application/pdf");
//        ossClient.putObject("<yourBucketName>", "<yourKey>", new ByteArrayInputStream(content.getBytes()), meta);
        PutObjectResult putObjectResult = ossClient.putObject(bucketName, fileName, inputStream, meta);
        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10000);
        URL url = ossClient.generatePresignedUrl(bucketName, fileName, expiration);
        // 关闭OSSClient。
        ossClient.shutdown();
//        log.debug(putObjectResult.toString());

        AliOssResponse aliOssResponse = new AliOssResponse();
        aliOssResponse.setPath(url.getPath());
        aliOssResponse.setAbsolutePath(aliOssRequest.getImgUrl() + url.getPath());
        return aliOssResponse;
    }
}
